package summary;

import java.util.*;

/**
 * @Author: 海琳琦
 * @Date: 2022/3/10 14:32
 * https://leetcode-cn.com/problems/most-frequent-subtree-sum/
 */
public class Title508 {

    class TreeNode {

        int val;

        TreeNode left;

        TreeNode right;

        public TreeNode() {
        }

        public TreeNode(int val) {
            this.val = val;
        }

        public TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    int max = 0;

    public int[] findFrequentTreeSum(TreeNode root) {
        Map<Integer, Integer> hash = new HashMap<>();
        dfs(root, hash);
        List<Integer> list = new ArrayList<>();
        Set<Integer> integers = hash.keySet();
        for (Integer temp : integers) {
            if (hash.get(temp) == max) {
                list.add(temp);
            }
        }
        int[] result = new int[list.size()];
        int count = 0;
        for (Integer a : list) {
            result[count++] = a;
        }
        return result;
    }

    private int dfs(TreeNode root, Map<Integer, Integer> hash) {
        if (root == null) {
            return 0;
        }
        int left = dfs(root.left, hash);
        int right = dfs(root.right, hash);
        int sum = left + right + root.val;
        hash.put(sum, hash.getOrDefault(sum, 0) + 1);
        max = Math.max(max, hash.get(sum));
        return sum;
    }

    public static void main(String[] args) {

    }
}
